
/**
 * ext-upload.js
 * 将编辑后的图片上传到影像系统中
 */
methodDraw.addExtension("server_upload", function(s) {

    var Utils = svgedit.utilities;
    
    var uploadHandler = function(svg) {
        //Editor.show_save_warning = false;

        // by default, we add the XML prolog back, systems integrating SVG-edit (wikis, CMSs) 
        // can just provide their own custom save handler and might not want the XML prolog
        svg = '<?xml version="1.0"?>\n' + svg;
        var ua = navigator.userAgent;
        // Chrome 5 (and 6?) don't allow saving, show source instead ( http://code.google.com/p/chromium/issues/detail?id=46735 )
        // IE9 doesn't allow standalone Data URLs ( https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves )
        // IE浏览器中文转换
        if (~ua.indexOf('MSIE')) {
            //不转换编辑图片的中文字符内容 xiliue 16.02.17
            var strone = svg.substring(0, svg.indexOf('<text xml:space'));
            var strtwo = svg.substring(svg.indexOf('<text xml:space'));
            strone = strone.replace(/([^\u0000-\u00FF])/g, function($) {
                return encodeURIComponent($);
            })
            svg = strone + strtwo;
        }

        

        var svgData = Utils.encode64(svg); // 图片的base64
        var flag = confirm("是否上传保存?");
        if (!flag) return;

        var imageSrc = decodeURIComponent($('#orignImg')[0].src);
        
        var URL = window.URL || window.webkitURL || window;

        if(!$('#export_canvas').length) {
            $('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
        }
        var canvas = $('#export_canvas')[0];

        var width=svgCanvas.contentW;
        var height = svgCanvas.contentH;
        canvas.width = width;
        canvas.height = height;
        var context = canvas.getContext('2d');

        //先将svg中的原图url替换为base64格式的dataUrl
        var image = new Image();
        image.onload = function() {
            context.drawImage(image, 0, 0, width, height ); //画背景图
            var orignImgData=canvas.toDataURL('image/jpeg');
            var newSvg=svg.replace(/xlink:href=\".*?\"/,'xlink:href="'+orignImgData+'"').replace('id="canvas_background"','display="none"')

            var blob = new Blob([newSvg],{type:'image/svg+xml;charset=utf-8'});
            var blobURL = URL.createObjectURL(blob);

            var svgImg=new Image();
            svgImg.onload=function(){
                //清空画布填充白色背景
                context.fillStyle="#ffffff";  
                context.beginPath();  
                context.fillRect(0, 0, width, height);  
                context.closePath();  

                context.drawImage(svgImg, 0, 0, width, height );
                context.save()

                canvas.toBlob(function(blob){
                    uploadFile(blob)
                }, 'image/jpeg', 0.95);

                // download(jpg, "image.jpg");
                
            }    
            svgImg.src=blobURL;
        };
        image.src = imageSrc;


        
    };
    return {
        name: "save",

        buttons: [{
            id: "file_upload",
            type: "menu",
            //after: "tool_wireframe",
            panel: "file_menu",
            title: "Save",
            events: {
                'click': function() {
                    // remove the selected outline before serializing
                    svgCanvas.clearSelection();
                    // no need for doctype, see http://jwatt.org/svg/authoring/#doctype-declaration
                    var str = svgCanvas.svgCanvasToString();
                    uploadHandler(str);
                }
            }
        }]
    };
});

/**
 * 判断一个变量是否是function类型
 */
function isFunction(fun) {
    return Object.prototype.toString.call(fun) === '[object Function]';
}

function getToken(){
    var t=sessionStorage.getItem('token');
    if(t){
        var token=JSON.parse(t);
        return token.v.replace("\"",'').replace("\"",'');
    }
    return ""
}
function download(href, name){
    var link = document.createElement('a');
    link.download = name;
    link.style.opacity = "0";
    document.body.appendChild(link);
    link.href = href;
    link.click();
    link.remove();
  }


function uploadFile(blob){
    var formData = new FormData();
    var filename="image" + new Date().getTime() + "_edit.jpg";
    formData.append('file', blob, filename);
    formData.append("operate", "edit");
    $.ajax({
        type: "POST",
        url: uploadUrl,
        headers: {
            'Authorization': getToken() 
        },
        xhrFields: {
            withCredentials: true
        },
        processData: false,
        contentType: false,
        data: formData,
        dataType: "json"
    })
    .done(function(d) {
        if (d.files && d.files.length === 1) {
            var file = {
                c_new_image_id: d.files[0].fileId,
                c_image_id: imageId,  //imageId为index.html定义的全局变量
                id: id //id为index.html定义的全局变量  Add By Liaolk36017 On 2021-12-8
            };
            saveToImg(file);
        }
        //解决ie 缓存问题
        //location.href = document.referrer+"&timeStamp=" + new Date().getTime();
        //history.back();
    })
    .fail(function(d) {
        alert("上传失败！");
    });
}


function saveToImg(file) {
    var url=uploadUrl.replace(/\/\w*?-service\/core\/file/,'/img-service/doc_collect/save_doc_info_edit')
   
    $.ajax({
        type: "POST",
        url: url,
        headers: {
            'Authorization': getToken() 
        },
        data: JSON.stringify(file),
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        success:function(data){
            alert('保存成功');
            //通知原页面刷新
            localStorage.setItem('reloadDocImg', file.c_image_id + '_reloadDocImg_' + new Date().getTime());
        },
        error:function(e){
            console.log(e)
            alert('保存成功')
        }
    })
};
